package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    private MapApi mapApi;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 获取默认地址
     *
     * @return 地址信息
     */
    @Override
    public AddressBookResDTO findDefaultAddress() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,UserContext.currentUserId())
                .eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(addressBook)){
            return null;
        }
        return BeanUtil.copyProperties(addressBook, AddressBookResDTO.class);

    }

    /**
     * 新增地址
     *
     * @param addressBookUpsertReqDTO 地址信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        //当前用户id
        Long userId = UserContext.currentUserId();

        //1. 如果新增地址设为默认，则将当前用户的其它地址设置为非默认
        if (1 == addressBookUpsertReqDTO.getIsDefault()) {
            //update address_book set is_default = 0 where user_id = 当前用户
            this.lambdaUpdate().set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, userId)
                    .update();
        }

        //2. 拷贝赋值
        AddressBook addressBook = BeanUtil.toBean(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setUserId(userId);

        //3. 如果请求体中没有经纬度，则调用第三方api根据详细地址获取经纬度
        if (ObjectUtil.isEmpty(addressBookUpsertReqDTO.getLocation())) {
            //组装详细地址
            String completeAddress = addressBookUpsertReqDTO.getProvince() +
                    addressBookUpsertReqDTO.getCity() +
                    addressBookUpsertReqDTO.getCounty() +
                    addressBookUpsertReqDTO.getAddress();
            //远程请求高德获取经纬度
            LocationResDTO locationDto = mapApi.getLocationByAddress(completeAddress);
            //经纬度(字符串格式：经度,纬度),经度在前，纬度在后
            String location = locationDto.getLocation();
            addressBookUpsertReqDTO.setLocation(location);
        }

        if (StringUtils.isNotEmpty(addressBookUpsertReqDTO.getLocation())) {
            // 经度
            addressBook.setLon(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[0]));
            // 纬度
            addressBook.setLat(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[1]));
        }

        //4. 执行保存操作
        getBaseMapper().insert(addressBook);
    }

    /**
     * 获取地址列表
     *
     * @param addressBookPageQueryReqDTO 地址信息
     * @return 地址列表
     */
    @Override
    public PageResult<AddressBookResDTO> page(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {

        //设置分页参数
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);

        //设置查询条件
        LambdaQueryWrapper<AddressBook> wrapper =
                Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId());

        //分页查询
        Page<AddressBook> serveTypePage = baseMapper.selectPage(page, wrapper);

        return PageUtils.toPage(serveTypePage, AddressBookResDTO.class);
    }

    /**
     * 根据id查询地址信息
     *
     * @param id 地址id
     * @return 地址信息
     */
    @Override
    public AddressBookResDTO getAddressInfo(Long id) {
        AddressBook addressBook = baseMapper.selectById(id);
        if (ObjectUtil.isNull(addressBook)) {
            return null;
        }
        AddressBookResDTO addressBookResDTO = BeanUtil.copyProperties(addressBook, AddressBookResDTO.class);
        return addressBookResDTO;
    }

    /**
     * 修改地址信息
     *
     * @param id                      地址id
     * @param addressBookUpsertReqDTO 地址信息
     */
    @Override
    public void update(Long id, AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        //1. 如果新增地址设为默认，则将当前用户的其它地址设置为非默认
        if (1 == addressBookUpsertReqDTO.getIsDefault()) {
            this.lambdaUpdate().set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .update();
        }

        //2. 拷贝赋值
        AddressBook addressBook = BeanUtil.toBean(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setId(id);

        //3. 如果请求体中没有经纬度，则调用第三方api根据详细地址获取经纬度
        if (ObjectUtil.isEmpty(addressBookUpsertReqDTO.getLocation())) {
            //组装详细地址
            String completeAddress = addressBookUpsertReqDTO.getProvince() +
                    addressBookUpsertReqDTO.getCity() +
                    addressBookUpsertReqDTO.getCounty() +
                    addressBookUpsertReqDTO.getAddress();
            //远程请求高德获取经纬度
            LocationResDTO locationDto = mapApi.getLocationByAddress(completeAddress);
            //经纬度(字符串格式：经度,纬度),经度在前，纬度在后
            String location = locationDto.getLocation();
            addressBookUpsertReqDTO.setLocation(location);
        }

        if (StringUtils.isNotEmpty(addressBookUpsertReqDTO.getLocation())) {
            // 经度
            addressBook.setLon(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[0]));
            // 纬度
            addressBook.setLat(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[1]));
        }

        //4. 执行修改
        baseMapper.updateById(addressBook);
    }

    /**
     * 批量删除
     *
     * @param ids 地址id列表
     */
    @Override
    public void removeByIds(List<Long> ids) {
        this.lambdaUpdate()
                .in(AddressBook::getId, ids)
                .set(AddressBook::getIsDeleted, 1)
                .update();
    }

    /**
     * 设置默认地址
     *
     * @param flag 1:设为默认 0:取消默认
     * @param id   地址id
     */
    @Override
    public void defaultAddress(Long flag, Long id) {
        //判断是不是默认地址
        if (flag == 1){
            this.lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .update();
        }
        this.lambdaUpdate()
                .set(AddressBook::getIsDefault, flag)
                .eq(AddressBook::getId, id)
                .update();
    }


}
